package com.ren.weibo.controller;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.ren.weibo.base.response.JsonResult;
import com.ren.weibo.base.response.StatusCode;
import com.ren.weibo.mapper.UserMapper;
import com.ren.weibo.pojo.dto.UserLoginParam;
import com.ren.weibo.pojo.dto.UserRegParam;
import com.ren.weibo.pojo.entity.User;
import com.ren.weibo.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;

@Slf4j
@RestController
@RequestMapping("/v1/user")
@Api(tags = "01.用户模块")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @ApiOperation("用户注册")
    @ApiOperationSupport(order = 10)
    @PostMapping("/reg")
    public JsonResult reg(@RequestBody @Validated UserRegParam userRegParam) {
        log.debug("userRegParam:"+userRegParam);
        String username = userRegParam.getUsername();
        int n = userMapper.selectByUsername(username);
        if (n == 1) {
            return new JsonResult(StatusCode.USERNAME_EXIST);
        }
        User user = new User();
        BeanUtils.copyProperties(userRegParam, user);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        userMapper.add(user);
        return JsonResult.ok();
    }

    @ApiOperation("用户登录")
    @ApiOperationSupport(order = 20)
    @PostMapping("/login")
    public JsonResult login(@RequestBody UserLoginParam userLoginParam, @ApiIgnore HttpSession session) {
        log.debug("userLoginParam:"+userLoginParam);
        String username = userLoginParam.getUsername();
        String password = userLoginParam.getPassword();
        UserVO userVO = userMapper.selectByUsernameAndPassword(username, password);
        if (userVO == null) {
            return new JsonResult(StatusCode.USERNAME_OR_PASSWORD_ERROR);
        }
        session.setAttribute("user", userVO);
        return JsonResult.ok();

    }

    @ApiOperation("获取当前登录用户")
    @ApiOperationSupport(order = 30)
    @GetMapping("/currentUser")
    public JsonResult currentUser(@ApiIgnore HttpSession session) {
        UserVO userVO = (UserVO) session.getAttribute("user");
        return new JsonResult(StatusCode.OPERATION_SUCCESS,userVO);

    }

    @ApiOperation("用户退出")
    @ApiOperationSupport(order = 40)
    @GetMapping("/logout")
    public JsonResult logout(@ApiIgnore HttpSession session) {
        session.removeAttribute("user");
        return new JsonResult(StatusCode.OPERATION_SUCCESS);
    }
}
